/*
 * @lc app=leetcode.cn id=1022 lang=typescript
 *
 * [1022] 从根到叶的二进制数之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function sumRootToLeaf(root: TreeNode | null): number {
    let result: number[] = [];
    const tra = (root: TreeNode | null, count = 0) => {
        if (!root) return;
        // 二进制累加转十进制的特殊操作
        const ThisVal = (count << 1) + root.val;
        if (!root.left && !root.right) {
            result.push(ThisVal);
        }
        tra(root.left, ThisVal);
        tra(root.right, ThisVal);
    };
    tra(root);
    return result.reduce((a, b) => a + b, 0);
}
// @lc code=end
